#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from persistent.mapping import PersistentMapping
from common.utils import LogUtil
from web_server.models.db_client import DBClient
from web_server.device_proxy import DeviceProxy

logger = LogUtil.get_logger(__name__)

class UserMgr:
    def __init__(self, device_proxy: DeviceProxy, db_client: DBClient):
        self.device_proxy = device_proxy
        self.db_client = db_client
        if not hasattr(self.db_client.root, 'users'):
            self.db_client.root.users = PersistentMapping()
            self.db_client.flush()
        self.users = self.db_client.root.users
        # 检查并创建默认admin用户
        self.__ensure_admin_user()

    def __del__(self):
        self.destroy()

    def destroy(self):
        self.db_client = None
        self.device_proxy = None
    
    def __ensure_admin_user(self):
        """确保admin用户存在，如果不存在则创建"""
        from .user import User
        
        admin_username = 'admin'
        
        # 检查admin用户是否已存在
        if admin_username not in self.users:
            try:
                logger.info("创建默认admin用户")
                
                # 创建admin用户
                admin_user = User(
                    username=admin_username,
                    email='admin@smartest.com'
                )
                
                # 设置密码为'admin'
                admin_user.set_password('admin')
                
                # 设置为管理员
                admin_user.is_admin = True
                admin_user.is_active = True
                
                # 保存到数据库
                self.users[admin_username] = admin_user
                self.db_client.flush()
                
                logger.info(f"admin用户创建成功")
                
            except Exception as e:
                logger.error(f"admin用户创建失败: {e}")
                raise e
        else:
            logger.debug("admin用户已存在，跳过创建")


    def get_user(self, username: str):
        """获取用户信息
        Args:
            username (str): 用户名
        Returns:
            User: 用户对象，如果用户不存在则返回 None
        """
        return self.users.get(username)
    
    def current_user(self):
        """获取当前用户信息
        Returns:
            User: 当前登录的用户对象，如果未登录则返回 None
        """
        username = self.device_proxy.session.get('username')
        if username is None:
            return None
        return self.get_user(username)